from django.conf import settings
from django.core import urlresolvers
from django.core.exceptions import ImproperlyConfigured
from apps.files.models import File
from apps.files.forms import FileForm
from apps.course.functions import course_reverse
from django.utils.importlib import import_module

DEFAULT_FILES_APP = 'apps.files'

class FilePostBadRequest(http.HttpResponseBadRequest):
    """
    Response returned when a file post is invalid. If ``DEBUG`` is on a
    nice-ish error message will be displayed (for debugging purposes), but in
    production mode a simple opaque 400 page will be displayed.
    """
    def __init__(self, why):
        super(FilePostBadRequest, self).__init__()
        if settings.DEBUG:
            self.content = render_to_string("files/400-debug.html", {"why": why})

def get_file_app():
    """
    Get the file app (i.e. "apps.files") as defined in the settings
    """
    # Make sure the app's in INSTALLED_APPS
    files_app = get_file_app_name()
    if files_app not in settings.INSTALLED_APPS:
        raise ImproperlyConfigured("The FILES_APP (%r) "\
                                   "must be in INSTALLED_APPS" % settings.FILES_APP)

    # Try to import the package
    try:
        package = import_module(files_app)
    except ImportError:
        raise ImproperlyConfigured("The FILES_APP setting refers to "\
                                   "a non-existing package.")

    return package

def get_file_app_name():
    """
    Returns the name of the file app (either the setting value, if it
    exists, or the default).
    """
    return getattr(settings, 'FILES_APP', DEFAULT_FILES_APP)

def get_model():
    """
    Returns the file model class.
    """
    if get_file_app_name() != DEFAULT_FILES_APP and hasattr(get_file_app(), "get_model"):
        return get_file_app().get_model()
    else:
        return File

def get_form():
    """
    Returns the file ModelForm class.
    """
    if get_file_app_name() != DEFAULT_FILES_APP and hasattr(get_file_app(), "get_form"):
        return get_file_app().get_form()
    else:
        return FileForm
    
def get_form_target():
    """
    Returns the target URL for the file form submission view.
    """
    if get_file_app_name() != DEFAULT_FILES_APP and hasattr(get_file_app(), "get_form_target"):
        return get_file_app().get_form_target()
    else:
        return urlresolvers.course_reverse("apps.files.views.files.post_file")

def is_content_object_invalid(request):
    # Look up the object we're trying to file about
    if request.method != "POST":
        return FilePostBadRequest("Missing POST data")
    data = request.POST
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return FilePostBadRequest("Missing content_type or object_pk field.")
    try:
        model = models.get_model(*ctype.split(".", 1))
        target = model._default_manager.using(using).get(pk=object_pk)
    except TypeError:
        return FilePostBadRequest(
            "Invalid content_type value: %r" % escape(ctype))
    except AttributeError:
        return FilePostBadRequest(
            "The given content-type %r does not resolve to a valid model." % \
                escape(ctype))
    except ObjectDoesNotExist:
        return FilePostBadRequest(
            "No object matching content-type %r and object PK %r exists." % \
                (escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError), e:
        return FilePostBadRequest(
            "Attempting go get content-type %r and object PK %r exists raised %s" % \
                (escape(ctype), escape(object_pk), e.__class__.__name__))
def save_form_data(request):
    assert False,request.GET
    get_form()

